package com.maomao.check;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.maomao.beans.*;
import com.maomao.db.DbConnection;

public class checkProcess {
	void  checkParameters(User user,HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		int temp = user.getUserType();
		String userType = null;
		if(temp==1)
			userType = "student";
		else if(temp == 2)
			userType = "teacher";
		else
			userType = "ta";
		
		String name = user.getName();
		String passwd = user.getPasswd();
		
		String sql="select * from person where Name = '"+name+"' and Password = '"+passwd+"' and userType = " +temp;
		System.out.println(sql);
		
		Boolean flag = isVacancy(sql);
		
//		DbConnection db = new DbConnection();
//		
//		int size=0;
//		
//		try {
//			size = db.getSzie(sql);
//			db.close();
////			System.out.println(size);
//		} catch (SQLException e2) {
//			// TODO Auto-generated catch block
//			e2.printStackTrace();
//		}
		
		if(flag)
		{
			
			
			sql =  "select * from person where Name = '"+name+"' and Password = '"+passwd+"' and userType = " +temp+" and isChecked = 1";
			flag = isVacancy(sql);
//			
//			try {
//				size = db.getSzie(sql);
//				db.close();
//			} catch (SQLException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
			
			if(flag)
			{
				HttpSession session = request.getSession();
				session.setAttribute("username", name);
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
				String logTime = dateFormat.format(new Date());
				
				session.setAttribute("logTime", logTime);
			
				
				Cookie cookie = new Cookie("username", name);
				
				cookie.setMaxAge(60*2);
				
				response.addCookie(cookie);
				response.sendRedirect("info/"+userType+"/welcome.html");
				
			}
			else
				out.println("<script language='javascript'>alert('����ע�ᣬ��δ����'); location='login.jsp';</script>");
		}
		else
			out.println("<script language='javascript'>alert('��δע��'); location='confirm.html';</script>");
			
	}
	
	boolean isVacancy(String sql)
	{
		DbConnection db = new DbConnection();
		
		int size=0;
		
		try {
			size = db.getSzie(sql);
			db.close();
//			System.out.println(size);
		} catch (SQLException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		
		if(size>0)
			return true;
		else
			return false;
	}
}
